package com.sunlee.admin.api.module.job.template;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sunlee.admin.api.module.job.template.context.CrawResourceCategoryContext;
import com.sunlee.common.service.entity.ThirdCategoryEntity;
import com.sunlee.common.service.service.ThirdCategoryService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 爬取第三方分类模板
 *
 * @author sunlee
 */
@Component
public abstract class CrawResourceCategoryTemplate {

    @Autowired
    private ThirdCategoryService thirdCategoryService;

    /**
     * 处理第三方一级分类，封装实体集合
     *
     * @param context 上下文
     */
    protected abstract void handleLeve1Category(CrawResourceCategoryContext context);

    /**
     * 处理第三方二级分类，封装实体集合
     *
     * @param context 上下文
     */
    protected abstract void handleLeve2Category(CrawResourceCategoryContext context);

    /**
     * 新增或更新第三方分类
     *
     * @param context 上下文
     */
    protected void saveOrUpdate(CrawResourceCategoryContext context) {
        List<ThirdCategoryEntity> newThirdCategoryList = context.getThirdCategoryList();

        if (CollectionUtils.isEmpty(newThirdCategoryList)) {
            return;
        }

        // 查询已经存在过的记录
        List<ThirdCategoryEntity> oldThirdList = thirdCategoryService.list(new LambdaQueryWrapper<ThirdCategoryEntity>()
                // 以下四个条件才组合唯一标识
                .eq(ThirdCategoryEntity::getSource, context.getSource())
                .in(ThirdCategoryEntity::getCategoryId, newThirdCategoryList.stream().map(ThirdCategoryEntity::getCategoryId).collect(Collectors.toList()))
                .in(ThirdCategoryEntity::getPid, newThirdCategoryList.stream().map(ThirdCategoryEntity::getPid).collect(Collectors.toList()))
                .in(ThirdCategoryEntity::getName, newThirdCategoryList.stream().map(ThirdCategoryEntity::getName).collect(Collectors.toList())));

        // 旧数据主键ID填充到新数据
        newThirdCategoryList = newThirdCategoryList.stream()
                .peek(newInfo -> {
                    Optional<ThirdCategoryEntity> oldInfoOptional = oldThirdList.stream()
                            .filter(oldInfo ->
                                    oldInfo.getCategoryId().equals(newInfo.getCategoryId())
                                            && oldInfo.getPid().equals(newInfo.getPid())
                                            && oldInfo.getName().equals(newInfo.getName()))
                            .findFirst();
                    if (oldInfoOptional.isPresent()) {
                        ThirdCategoryEntity oldInfo = oldInfoOptional.get();
                        newInfo.setId(oldInfo.getId());
                        // 状态不修改
                        newInfo.setStatus(oldInfo.getStatus());
                        // 备注：新备注为空，则用旧备注
                        if (StringUtils.isBlank(newInfo.getRemark())) {
                            newInfo.setRemark(oldInfo.getRemark());
                        }
                    }
                })
                .collect(Collectors.toList());

        // 批量保存
        thirdCategoryService.saveOrUpdateBatch(newThirdCategoryList);
    }

    public final void process(CrawResourceCategoryContext context) {
        // 流程开始处理前，进行初始化操作
        init(context);

        // 处理一级分类
        handleLeve1Category(context);

        // 处理二级分类
        handleLeve2Category(context);

        //流程处理结束后，进行收尾操作
        end(context);
    }

    /**
     * 流程开始处理前，进行初始化操作
     *
     * @param context 上下文
     */
    protected void init(CrawResourceCategoryContext context) {
    }

    /**
     * 流程处理结束后，进行收尾操作
     *
     * @param context 上下文
     */
    protected void end(CrawResourceCategoryContext context) {
    }
}
